#region Using directives
using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
#endregion

namespace SharpWind.Resources.Scripts
{
	internal class ScriptCompiler
	{
		#region Fields

		private static readonly ScriptCompiler defaultCompiler = new ScriptCompiler();

		private CSharpCodeProvider codeProvider = null;

		private CompilerParameters compilerParams = null;

		#endregion

		#region Constructor

		private ScriptCompiler()
		{
			this.codeProvider = new CSharpCodeProvider();

			this.compilerParams = new CompilerParameters();
			this.compilerParams.GenerateExecutable		= false;
			this.compilerParams.GenerateInMemory		= true;
			this.compilerParams.IncludeDebugInformation = false;
			this.compilerParams.TreatWarningsAsErrors	= false;
			this.compilerParams.ReferencedAssemblies.Add( "Microsoft.DirectX.dll" );
			this.compilerParams.ReferencedAssemblies.Add( "Microsoft.DirectX.Direct3D.dll" );
			this.compilerParams.ReferencedAssemblies.Add( "Microsoft.DirectX.Direct3DX.dll" );
			this.compilerParams.ReferencedAssemblies.Add( "SharpWind.dll" );
		}

		#endregion

		#region Methods

		public Assembly Compile( string[] referencedAssembiles, string source )
		{
			this.compilerParams.ReferencedAssemblies.AddRange( referencedAssembiles );

			CompilerResults results = this.codeProvider.CompileAssemblyFromSource( this.compilerParams, source );
			if( results.Errors.HasErrors )
			{
				return null;
			}

			return results.CompiledAssembly;
		}

		#endregion

		#region Properties

		public static ScriptCompiler DefaultCompiler
		{
			get
			{
				return defaultCompiler;
			}
		}

		#endregion
	}
}
